/**
 * 作者: 陈辉
 * 描述: 用户管理
 * 日期：2019-07-24
 */

(function(E, KIT, RES) {
  var URL_ROOT = RES.URL_ROOT + "/user",
    URL_FIND = URL_ROOT + "/getUsers",
    URL_ADD = URL_ROOT + "/addUser",
    URL_UPDATE = URL_ROOT + "/updateUser",
    URL_REMOVE = URL_ROOT + "/removeUsers",
      URL_TBKHSJ = URL_ROOT + "/tbkhsj",
    URL_FIND_GROUP_BY_USER = URL_ROOT + "/getUserGroupRelationByUserId",
    URL_SET_GROUP = URL_ROOT + "/setUserGroupRelation",
    URL_FIND_ALL_ROLE = URL_ROOT + "/getAllRoleInfo",
    URL_SET_ROLE = URL_ROOT + "/setUserRoleRelation",
    URL_FIND_ROLE_BY_USER = URL_ROOT + "/getUserRoleRelationByUserId",
    URL_CHANGE_STATE = URL_ROOT + "/changeState",
      URL_AUDITS= URL_ROOT + "/auditS",
    URL_CHANGE_LOGIN = URL_ROOT + "/changeLogin",
    URL_RESET_PWD = URL_ROOT + "/resetPassword",
    URL_EXPORT = URL_ROOT + "/exportUsers",
    URL_GET_GROUP_TREE = URL_ROOT + "/getjsTreeByGroup",
    URL_SET_GROUP_DATA = URL_ROOT + "/setUserGroupDataRelation";

  var DS_USER_TYPE = RES.ENUM_USER_TYPES.getArr();

  var GRID_FIELDS = [{
    title: "账号", name: "login_id", width: 100, editor: {
      validator: {
        rules: {required: true, maxlength: 20}
      }
    }
  }, {
    title: "名称", name: "name", width: 100, editor: {
      validator: {
        rules: {required: true, maxlength: 40}
      },

    }
  }, {
    title: "身份证号", name: "card_id", width: 120, editor: {
      validator: {
        rules: {required: true, maxlength: 18}
      },

    }
  }, {
    title: "类型", name: "user_typ", width: 80,
    formatter: function(value) {
      return RES.ENUM_USER_TYPES.getText(value);
    },
    editor: {
      name: "user_typ",
      type: "picker",
      tip: "请选择...",
      dataSource: DS_USER_TYPE,
      validator: {
        rules: {required: true}
      }
    }
  }, {
    title: "统一ID", name: "row_id", width: 120, editor: false
  }, {
    title: "可信帐户", name: "trust_account", width: 200, editor: false
  },{
    title: "可信账户私钥", name: "accountprivatekey", width: 200, editor: false
  }, {
    title: "数据状态", align: "center", width: 80,
    formatter: function(value, text, css) {
      css.color = value == 1 ? null : 6;
      return value == 1 ? "启用" : "禁用";
    },
    editor: {
      name: "enabled", type: "radiolist", defaultValue: 1,
      dataSource: [{text: "启用", value: 1}, {text: "禁用", value: 0}]
    }
  }, {
    title: "登录状态", width: 80, align: "center",
    formatter: function(value, text, css) {
      css.color = value == 1 ? null : 6;
      return value == 1 ? "允许" : "禁止";
    },
    editor: {
      name: "canlogin", type: "radiolist", defaultValue: 1,
      dataSource: [{text: "允许", value: 1}, {text: "禁止", value: 0}]
    }
  }, {
    title: "电话", name: "phone", width: 80, visible: false, editor: true
  },{
    title: "备注", name: "note", width: 60, visible: false, editor: true
  }];

  //region private
  var _filterAdmin = function(item) {
    return item.login_id !== RES.ADMIN_USER_LOGIN_ID;
  };

  //新增
  var _btnAddUser = function(e) {
    var __grid = this;
    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {

        rapid.post({
          url: URL_ADD,
          data: KIT.getEncryptParams(e.serializeJson()),
          success: function(result) {
            e.hide();
            __grid.reload();
          }
        });
      }
    });
  };

  //修改
  var _btnUpdateUser = function(e) {
    var __grid = this;
    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {
        rapid.post({
          url: URL_UPDATE,
          data: KIT.getEncryptParams(e.serializeJson()),
          success: function(result) {

            e.hide();
            __grid.reload();
          }
        });
      }
    });
  };

  // 更改状态
  var _changeState = function(grid, id, state) {
    rapid.post({
      url: URL_CHANGE_STATE,
      data: {
        userids: id.toString(),
        state: state
      },
      success: function(result) {
        switch(result) {
          case 0:
            rapid.success("操作成功！", function() {
              grid.reload();
            }, false);
            break;
          case -1:
            rapid.warning("当前信息已被删除，不可修改。", function() {
              grid.reload();
            }, false);
            break;
          default:
            rapid.error("保存失败。", function() {
              grid.reload();
            }, false);
            break;
        }
      }
    });
  };


  var _Audits = function(grid, id) {
    rapid.post({
      url: URL_AUDITS,
      data: {
        userids: id.toString()
      },
      success: function(result) {
        rapid.success("操作成功！", function() {
          grid.reload();
        }, false);
      }
    });
  };

  // 重置密码
  var _resetPassword = function(grid, id) {
    if(id) {
      rapid.post({
        url: URL_RESET_PWD,
        data: {
          userids: id.toString()
        },
        success: function(result) {
          switch(result) {
            case 0:
              rapid.success("操作成功！", function() {
                grid.reload();
              }, false);
              break;
            case -1:
              rapid.warning("当前信息已被删除，不可修改。", function() {
                grid.reload();
              }, false);
              break;
            default:
              rapid.error();
              break;
          }
        }
      });
    }
  };

  // 更改是否可以登录状态
  var _changeLogin = function(grid, ids, LoginState) {
    rapid.post({
      url: URL_CHANGE_LOGIN,
      data: {
        userids: ids.toString(),
        state: LoginState
      },
      success: function(result) {
        switch(result) {
          case 0:
            rapid.success("操作成功！", function() {
              grid.reload();
            }, false);
            break;
          case -1:
            rapid.warning("当前信息已被删除，不可修改。", function() {
              grid.reload();
            }, false);
            break;
          default:
            rapid.error("保存失败。", function() {
              grid.reload();
            }, false);
            break;
        }
      }
    });
  };

  var _changeGroup = function(app, uid) {
    app.tag("userid", uid);
    rapid.post({
      url: URL_FIND_GROUP_BY_USER,
      data: "Id=" + uid,
      success: function(result) {
        _groupSetTree().checknodes(result);
        _groupSetTree().openall();

        rapid("#winUserGroup").window().show();
      }
    });
  };

  var _groupSearchTree = function(options) {
    if(arguments.length === 1) {
      return $("#treeGroupSearch").g_jstree(rapid.nvl(options, {}));
    }
    return $("#treeGroupSearch").g_jstree();
  };

  var _groupSetTree = function(options) {
    if(arguments.length === 1) {
      return $("#treeGroupSet").g_jstree(rapid.nvl(options, {}));
    }
    return $("#treeGroupSet").g_jstree();
  };

  var _groupDataSetTree = function(options) {
    if(arguments.length === 1) {
      return $("#treeGroupDataSet").g_jstree(rapid.nvl(options, {}));
    }
    return $("#treeGroupDataSet").g_jstree();
  };

  //endregion


  rapid.Page.create({
    render: {
      titleBar: "用户管理",
      other: E.block(
        E.window("wndRole",
          E.dataview("frmRole")
        )
      )
    },

    methods: {
      _initEly_: function() {
        rapid("#frmRole").dataview({
          paramFields: ["conflict_id"],
          colSize: 1,
          fields: [{
            title: "角色", name: "name", width: 220, editor: {
              name: "roleIds",
              type: "picker",
              tip: "请选择...",
              editable: true,
              multiple: true,
              dataSource: {
                textField: "name",
                valueField: "id",
                url: URL_FIND_ALL_ROLE
              },
              autocomplete: {
                paramName: "search_name",
                dataSource: {
                  textField: "name",
                  valueField: "id",
                  url: URL_FIND_ALL_ROLE
                }
              }
            }
          }]
        });
      },
      _changeRole: function(app, uid) {
        var __grid = this;
        rapid("#wndRole").window({
          title: "设置角色",
          size: "xs",
          buttons: [{
            "保存": function(e) {
              var s = this;
              var __dataview = rapid("#frmRole").dataview();

              if(!__dataview.valid()) {
                return;
              }
              rapid.confirm("确定要保存吗？", function(e) {
                var data = __dataview.serializeJson();
                data.userId = uid;
                if(e) {
                  rapid.post({
                    id: "getRoleSave",
                    url: URL_SET_ROLE,
                    data: data,
                    success: function(result) {
                      s.hide();
                      __grid.reload();
                    }
                  });
                }
              });
            }
          }],
          onShow: function() {
            rapid.post({
              url: URL_FIND_ROLE_BY_USER,
              data: "Id=" + uid,
              success: function(result) {
                var __dv = rapid("#frmRole").dataview();
                var ss = [];
                ss = result;
                var keys = [];
                var values = [];
                if(result != null) {
                  for(var i = 0; ss.length > i; i++) {
                    keys.push(ss[i].id);
                    values.push(ss[i].name)
                  }
                }
                __dv.ui("roleIds").text(values).value(keys);
              }
            });
          },
          onHide: function() {
            rapid("#frmRole").dataview().reset();
          }
        }).show();
      },

      _initPicker_: function() {

        rapid("#comSearchUserCode").picker({
          tip: "请选择",
          dataSource: DS_USER_TYPE
        });

        rapid("#comSearchUserType").picker({
          tip: "请选择",
          dataSource: DS_USER_TYPE
        });

        rapid("#roleCheckBoxListSearch").picker({
          tip: "请选择",
          multiple: true,
          dataSource: {
            textField: "name",
            valueField: "id",
            url: URL_FIND_ALL_ROLE
          }
        });

      },
      _initGroupTree_: function() {

        _groupSetTree({
          checkbox: true,
          data: {
            url: URL_GET_GROUP_TREE
          }
        });

        /* $("#treeGroupSet").on("select_node.jstree", function(e, data) {
           var __node = data.node,
             __tree = data.instance;

           var __selected = data.selected,
             __len = __selected.length;

           for(var __i = 0; __i < __len; __i++) {
             if(__selected[__i] != __node.id) {
               __tree.uncheck_node(__selected[__i]);
             }
           }
         }); */

        _groupSearchTree({
          checkbox: true,
          data: {
            url: URL_GET_GROUP_TREE
          }
        });

        return this;
      },

      _initGroupDataTree_: function() {
        _groupDataSetTree({
          checkbox: true,
          data: {
            url: URL_GET_GROUP_TREE
          }
        });

        return this;
      },

      _bindTreeOpenAndCloseEvent_: function() {

        rapid.ui("#btnOpenAllTreeSearch").on("click", function() {
          _groupSearchTree().openall();
        });

        rapid.ui("#btnCloseAllTreeSearch").on("click", function() {
          _groupSearchTree().closeall();
        });

        rapid.ui("#btnCheckedAllTreeSearch").on("click", function() {
          _groupSearchTree().checkall();
        });

        rapid.ui("#btnUncheckedAllTreeSearch").on("click", function() {
          _groupSearchTree().uncheckall();
        });

        rapid.ui("#btnOpenAllTreeSet").on("click", function() {
          _groupSetTree().openall();
        });

        rapid.ui("#btnCloseAllTreeSet").on("click", function() {
          _groupSetTree().closeall();
        });

        rapid.ui("#btnCheckedAllTreeSet").on("click", function() {
          _groupSetTree().checkall();
        });

        rapid.ui("#btnUncheckedAllTreeSet").on("click", function() {
          _groupSetTree().uncheckall();
        });

        rapid.ui("#btnOpenAllTreeSetGD").on("click", function() {
          _groupDataSetTree().openall();
        });

        rapid.ui("#btnCloseAllTreeSetGD").on("click", function() {
          _groupDataSetTree().closeall();
        });

        rapid.ui("#btnCheckedAllTreeSetGD").on("click", function() {
          _groupDataSetTree().checkall();
        });

        rapid.ui("#btnUncheckedAllTreeSetGD").on("click", function() {
          _groupDataSetTree().uncheckall();
        });
        return this;
      },

      _initSetGroupWindow_: function() {
        var __app = this;
        rapid("#winUserGroup")
          .window({
            title: "设置机构",
            size: "sm",
            buttons: [{
              "保存": function() {
                var __check_ids = _groupSetTree().getchecked();

                if(rapid.isEmpty(__check_ids)) {
                  rapid.warning("请选择机构。");

                } else {
                  var __ui_wnd = this;

                  rapid.post({
                    url: URL_SET_GROUP,
                    data: {
                      userId: __app.tag("userid"),
                      groupIds: __check_ids.toString()
                    },
                    success: function(result) {
                      __ui_wnd.hide();
                      rapid.success();
                    }
                  });
                }
              }
            }]
          })
          .on("hide", function() {
            __app.tag("userid", null);
            _groupSetTree().uncheckall();
          });

        return this;
      },

      _initSetDataPermissionWindow_: function() {
        var __app = this;

        rapid("#winUserGroupData")
          .window({
            title: "设置数据权限",
            size: "sm",
            buttons: [{
              "保存": function() {
                var __ui_wnd = this;

                var __check_ids = _groupDataSetTree().getchecked();

                rapid.post({
                  url: URL_SET_GROUP_DATA,
                  data: {
                    userId: __app.tag("userid"),
                    groupIds: __check_ids.toString()
                  },
                  success: function(result) {
                    if(result == 0) {
                      __ui_wnd.hide();
                      rapid.success();
                    } else {
                      rapid.error("保存失败。");
                    }
                  }
                });
              }
            }]
          })
          .on("hide", function() {
            __app.tag("userid", null);
            _groupDataSetTree().uncheckall();
          });
      },

      _initUi_: function() {
        //搜索
        rapid.ui("#btnSearch").on("click", function() {
          var _searchParams = rapid("#searchUserFrm").serializeJson();
          var _groups = _groupSearchTree().getbottomchecked().toString();

          var group = _searchParams.groups = _groups.toString();
          var names = _searchParams.name;
          var loginId = _searchParams.loginId;
          var userCode = _searchParams.userCode;

          var __query_roleIds = _searchParams.roleIds;

          /*          if(rapid.hasValue(__query_roleIds)) {
                      if(rapid.isArray(__query_roleIds)) {
                        __query_roleIds = "'" + __query_roleIds.join("','") + "'";
                      } else {
                        __query_roleIds = "'" + __query_roleIds + "'";
                      }

                      _searchParams.roleIds = __query_roleIds;
                    }*/

          rapid("#grd").grid().load({
            data: {
              loginId: loginId,
              name: names,
              userCode: userCode,
              roleIds: __query_roleIds,
              groups: group
            }
          });
        });

        //清空
        rapid.ui("#btnSearchClear").on("click", function() {
          rapid.ui("#txtSearchLoginId").val("");
          rapid.ui("#txtSearchName").val("");

          //清空人员
          rapid.ui("#comSearchUserCode").val("");
          rapid.ui("#roleCheckBoxListSearch").val("");

          _groupSearchTree().uncheckall();

        });
      },

      //多选操作
      _getGridMultiActions_: function() {
        return [{
          toolbar: true,
          text: "启用",
          filter: _filterAdmin,
          handler: function() {
            _changeState(this, this.keySelection(), "1");
            return true;
          }
        }, {
          toolbar: true,
          text: "禁用",
          filter: _filterAdmin,
          handler: function() {
            _changeState(this, this.keySelection(), "0");
            return true;
          }
        }, {
          toolbar: true,
          text: "允许登录",
          filter: _filterAdmin,
          handler: function() {
            _changeLogin(this, this.keySelection(), "1");
            return true;
          }
        }, {
          toolbar: true,
          text: "禁止登录",
          filter: _filterAdmin,
          handler: function() {
            _changeLogin(this, this.keySelection(), "0");
            return true;
          }
        }, {
          toolbar: true,
          text: "重置密码",
          filter: _filterAdmin,
          handler: function() {
            _resetPassword(this, this.keySelection());
            return true;
          }
        },{
          toolbar: true,
          text: "创建用户",
          color:12,
          filter: _filterAdmin,
          handler: function() {
            _Audits(this, this.keySelection());
            return true;
          }
        }];
      },

      //单选操作
      _getGridSingeActions_: function() {
        var __app = this;
        return [{
          text: "分配机构",
          filter: _filterAdmin,
          handler: function() {
            _changeGroup(__app, this.selection()[0].ui().id.val());
          }
        }, {
          text: "分配角色",
          filter: _filterAdmin,
          handler: function() {
            __app._changeRole(__app, this.selection()[0].ui().id.val());
          }
        },{
          text: "导出可信账户私钥",
          filter: _filterAdmin,
          handler: function() {
            console.log(this.selection()[0].ui());
            alert(this.selection()[0].ui().accountprivatekey.val())
          }
        }]
      },

      // 表格事件
      _initGridEvent_: function() {
        rapid("#grd").grid()
                     .on("add", _btnAddUser)
                     .on("update", _btnUpdateUser)
                     .on("remove", function(ids) {
                       var __grid = this;
                       var _hasAdminUser = false;
                       for(var i = 0; i < ids.length; i++) {
                         if("1" == ids[i]) {
                           _hasAdminUser = true;
                           ids.splice(i, 1);
                         }
                       }
                       rapid.post({
                         url: URL_REMOVE,
                         data: "ids=" + ids,
                         success: function() {
                           __grid.reload();
                         }
                       });
                     }).on("beforeUpdate",function (dateview) {
                       dateview.ui("card_id").disabled(true);
                        dateview.ui("name").disabled(true);

        });
      },

      // 初始化表格
      _initGrid_: function() {
        var __app = this;

        rapid("#grd").grid({
          height: function() {
            return rapid(__app.main()).height();
          },
          addable: true,
          updatable: {
            filter: _filterAdmin
          },
          removable: {
            filter: _filterAdmin
          },
          detailed: true,

          dataSource: {
            url: URL_FIND
          },
          pageable: true,
          keyFields: "id",
          paramFields: ["id"],
          singleActions: this._getGridSingeActions_(),
          multiActions: this._getGridMultiActions_(),
          actions: [{
            text: "导出",
            toolbar: true,
            handler: function() {
              var _groups = _groupSearchTree().getbottomchecked();
              if(_groups.length > 0) {
                _groups = _groups.join("','");
                _groups = "'" + _groups + "'";
              } else {
                _groups = "";
              }

              var query = rapid("#searchUserFrm").serialize();
              window.location.href = URL_EXPORT + "?" + query + "&groups=" + _groups;
            }
          }],
          fields: GRID_FIELDS
        }).load();

        this._initGridEvent_();
      }
    }

  })(function() {
    this._initUi_();
    this._initSetGroupWindow_();
    this._initSetDataPermissionWindow_();
    this._initGrid_();
    this._initGroupTree_();
    this._initGroupDataTree_();
    this._bindTreeOpenAndCloseEvent_();
    this._initEly_();
    this._initPicker_();

  }).init();

})(rapid.html.Element, rapid.kit, rapid.res);

